// pages/videoInfo/videoInfo.js
const videoUtils = require('../../utils/videoUtils.js');
var videoUtil = require('../../utils/videoUtils.js');
const app = getApp();
Page({
  data: {
    cover: "cover",
    src: "",
    videoId: "",
    videoInfo: {},
    userLikeVideo: false,
    faceImage: "",
    commentsPage: 1,
    commentsTotalPage: 0,
    commentsList: [],
    placeholder: "说点什么..."
  },
  videoCtx: {},
  onLoad: function (params) {
    var me = this;
    var videoInfo = JSON.parse(params.videoInfo);
    //console.log(videoInfo);
    var src = videoInfo.videoPath;
    var serverUrl = app.serverUrl;
    var videoHeight = videoInfo.videoHeight;
    var videoWidth = videoInfo.videoWidth;
    var cover = "cover";
    if (videoWidth >= videoHeight) {
      cover = ""
    }
    me.setData({
      src: serverUrl + src,
      videoId: videoInfo.id,
      videoInfo: videoInfo,
      cover: cover
    })
    me.videoCtx = wx.createVideoContext("myVideo", me);
    var serverUrl = app.serverUrl;
    var user = app.getGlobalUserInfo();
    var loginUserId = "";
    if (user != null && user != undefined && user != '') {
      loginUserId = user.id;
    }
    wx.request({
      url: serverUrl + "/user/queryPublisher?loginUserId=" + loginUserId + '&videoId=' + videoInfo.id + '&publisherUserId=' + videoInfo.userId,
      method: 'POST',
      success: function (res) {
        //console.log(res.data);
        var data = res.data.data;
        var publisherVideo = data.userVo;
        var isLike = data.isLike;
        //获取最新评论
        me.getCommentsList(1);
        me.setData({
          faceImage: serverUrl + publisherVideo.faceImage,
          userLikeVideo: isLike
        })
      }
    })
  },
  onShow: function () {
    var me = this;
    me.videoCtx.play();
  },
  onHide: function () {
    var me = this;
    me.videoCtx.pause();
  },
  showSearch: function () {
    wx.navigateTo({
      url: '../searchVideo/searchVideo',
    })
  },
  upload: function () {
    var me = this;
    var user = app.getGlobalUserInfo();
    var tempInfo = JSON.stringify(me.data.videoInfo);
    if (user == null || user == undefined || user == "") {
      wx.navigateTo({
        url: '../userLogin/login?info=' + tempInfo,
      })
    } else {
      videoUtil.uploadVideo();
    }

  },
  showIndex: function () {
    wx.redirectTo({
      url: '../index/index',
    })
  },
  showMine: function () {
    var me = this;
    var user = app.getGlobalUserInfo();
    if (user == null || user == undefined || user == "") {
      var tempInfo = JSON.stringify(me.data.videoInfo);
      wx.redirectTo({
        url: '../userLogin/login?info=' + tempInfo,
      })
    } else {
      wx.navigateTo({
        url: '../mine/mine?userId=' + user.id,
      })
    }
  },
  showPublisher: function () {
    var me = this;
    var user = app.getGlobalUserInfo();
    var videoInfo = me.data.videoInfo;
    if (user == null || user == undefined || user == "") {
      var tempInfo = JSON.stringify(videoInfo);
      wx.navigateTo({
        url: '../userLogin/login?info=' + tempInfo,
      })
    } else {
      wx.navigateTo({
        url: '../mine/mine?publisherId=' + videoInfo.userId,
      })
    }
  },
  likeVideoOrNot: function () {
    var me = this;
    var videoInfo = me.data.videoInfo;
    var user = app.getGlobalUserInfo();
    if (user == null || user == undefined || user == "") {
      var tempInfo = JSON.stringify(me.data.videoInfo);
      wx.navigateTo({
        url: '../userLogin/login?info=' + tempInfo,
      })
    } else {
      var url = '/video/userLike?userId=' + user.id + '&videoId=' + videoInfo.id + '&videoOwnId=' + videoInfo.userId;
      var userlikeVideo = me.data.userLikeVideo;
      if (userlikeVideo) {
        url = '/video/userUnLike?userId=' + user.id + '&videoId=' + videoInfo.id + '&videoOwnId=' + videoInfo.userId;
      }
      var serverUrl = app.serverUrl;
      wx.showLoading({
        title: '...',
      })
      wx.request({
        url: serverUrl + url,
        method: 'POST',
        header: {
          'content-type': 'application/json',
          'userId': user.id,
          'userToken': user.userToken
        },
        success: function (res) {
          wx.hideLoading();
          me.setData({
            userLikeVideo: !userlikeVideo
          });
        }
      })
    }
  },
  shareMe: function () {
    var me = this;


    wx.showActionSheet({
      itemList: ['下载到本地', '举报用户', '分享到朋友圈'],
      success: function (res) {
        //console.log(res.tapIndex);
        if (res.tapIndex == 0) {
          //下载视频
          var serverUrl = app.serverUrl;
          var videoPath = me.data.videoInfo.videoPath;
          wx.showLoading({
            title: "请等待..."
          })
          wx.downloadFile({
            url: serverUrl + videoPath, //仅为示例，并非真实的资源
            success(res) {
              // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
              if (res.statusCode === 200) {
                //console.log(res.tempFilePath)
                wx.saveVideoToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: function (res) {
                    //console.log(res),
                    wx.hideLoading()
                  }
                })
              }
            }
          })

        } else if (res.tapIndex == 1) {
          //举报视频
          var user = app.getGlobalUserInfo();
          var videoInfo = me.data.videoInfo;
          if (user == null || user == undefined || user == "") {
            //未登录用户先登录
            var tempInfo = JSON.stringify(videoInfo);
            wx.navigateTo({
              url: '../userLogin/login?info=' + tempInfo,
            })
          } else {
            var publisherId = me.data.videoInfo.userId;
            var videoId = me.data.videoInfo.id;
            var currentUserId = user.id;
            wx.navigateTo({
              url: '../report/report?videoId=' + videoId + '&publisherId=' + publisherId + '&currentUserId=' + currentUserId,
            })
          }
        } else {
          //分享视频
        }
      }
    })
  },
  onShareAppMessage: function (res) {
    var me = this;
    var videoInfo = me.data.videoInfo;
    return {
      title: "短视屏分享",
      path: "pages/videoInfo/videoInfo?videoInfo=" + JSON.stringify(videoInfo)
    }
  },
  //显示评论框
  leaveComment: function () {
    var me = this;
    me.setData({
      commentFocus: true
    })
  },
  //获取回复相关信息
  replyFocus: function(e){
    var me = this;
  var fatherCommentId= e.currentTarget.dataset.fathercommentid;
  var toUserId= e.currentTarget.dataset.touserid;
  var toNickname= e.currentTarget.dataset.tonickname;
  me.setData({
    placeholder: "回复" + toNickname,
    replyFatherCommentId: fatherCommentId,
    replyToUserId: toUserId,
    commentFocus: true
  })
  },
  //保存评论
  saveComment: function (e) {
    var me = this;
    var fatherCommentId = e.currentTarget.dataset.replyfathercommentid;
    var toUserId = e.currentTarget.dataset.replytouserid;
    var content = e.detail.value;
    var user = app.getGlobalUserInfo();
    var videoInfo = me.data.videoInfo;
    var serverUrl = app.serverUrl;
    if (user == null || user == undefined || user == "") {
      var tempInfo = JSON.stringify(me.data.videoInfo);
      wx.navigateTo({
        url: '../userLogin/login?info=' + tempInfo,
      })
    } else {
      wx.showLoading({
        title: '请等一下...',
      })
      wx.request({
        url: serverUrl + '/video/saveComments',
        method: "POST",
        data: {
          fromUserId: user.id,
          videoId: videoInfo.id,
          comment: content,
          fatherCommentId: fatherCommentId,
          toUserId: toUserId
        },
        header: {
          'content-type': 'application/json',
          'userId': user.id,
          'userToken': user.userToken
        },
        success: function (res) {
          wx.hideLoading()
          //console.log(res.data)
          var status = res.data.status;
          if (status == 200) {
            me.setData({
              contentValue: "",
              commentsList: []
            })
            me.getCommentsList(1);

          } else if (status == 502) {
            //未登录用户
            wx.showToast({
              title: res.data.msg,
            })
            //跳转到登录页
            var tempInfo = JSON.stringify(me.data.videoInfo);
            wx.navigateTo({
              url: '../userLogin/login?info=' + tempInfo,
            })
          }
        }
      })
    }
  },
  getCommentsList: function (page) {
    // commentsPage: 1,
    // commentsTotalPage: 0,
    // commentsList:[]
    var me = this;
    var videoId = me.data.videoId;
    wx.request({
      url: app.serverUrl + '/video/getAllComments?videoId=' + videoId + '&page=' + page + '&pageSize=6',
      method: "POST",
      success: function (res) {
        console.log(res.data);
        var commentsList = res.data.data.rows;
        var newcommentsList = me.data.commentsList;
        me.setData({
          commentsList: newcommentsList.concat(commentsList),
          commentsPage: page,
          commentsTotalPage: res.data.data.total,
          serverUrl: app.serverUrl
        });
      }
    })
  },
  //上拉刷新
  onReachBottom: function () {
    var me = this;
    var currentPage = me.data.commentsPage;
    var totalPage = me.data.commentsTotalPage;

    //判断是否到了最后一页
    if (totalPage == currentPage) {
      wx.showToast({
        title: '没有了哦~',
        icon: "none"
      })
      return;
    };
    var page = currentPage + 1;
    me.getCommentsList(page);
  },
  // onPullDownRefresh: function() {
  //   // Do something when pull down.
  //   wx.showLoading({
  //     title: 'hahah',
  //   })
  //   wx.showNavigationBarLoading();
  //   wx.hideNavigationBarLoading();
  //   wx.stopPullDownRefresh();
  //   wx.hideLoading();
  // }
})